// status_table.h
#ifndef STATUS_TABLE_H
#define STATUS_TABLE_H

#include <QString>
#include <QDateTime>
#include <QVariantMap>

// 运行状态枚举
enum class RunStatus : int {
    Idle = 0,           // 空闲
    Initialized = 1,    // 初始化完成
    Running = 2,        // 运行
    Paused = 3,         // 暂停
    Stopped = 4         // 停止
};

// 报警状态枚举
enum class AlarmStatus : int {
    NoAlarm = 0,        // 无报警
    HasAlarm = 1        // 有报警
};

// 控制方式枚举
enum class ControlMode : int {
    Local = 0,          // 本地
    Remote = 1          // 远程
};

// 机台模式枚举
enum class MachineMode : int {
    Manual = 0,         // 手动
    Auto = 1,           // 自动
    SingleStep = 2,     // 单步
    Debug = 3,          // 调试
    Maintenance = 4     // 维护
};

// 坐标结构体
struct Coordinate {
    double x;
    double y;
    double z;

    Coordinate() : x(0.0), y(0.0), z(0.0) {}
    Coordinate(double x, double y, double z) : x(x), y(y), z(z) {}

    QString toString() const {
        return QString("%1,%2,%3").arg(x, 0, 'f', 3).arg(y, 0, 'f', 3).arg(z, 0, 'f', 3);
    }

    static Coordinate fromString(const QString& str) {
        Coordinate coord;
        QStringList parts = str.split(',');
        if (parts.size() == 3) {
            coord.x = parts[0].toDouble();
            coord.y = parts[1].toDouble();
            coord.z = parts[2].toDouble();
        }
        return coord;
    }

    bool isValid() const {
        return !std::isnan(x) && !std::isnan(y) && !std::isnan(z);
    }

    bool operator==(const Coordinate& other) const {
        return qFuzzyCompare(x, other.x) &&
               qFuzzyCompare(y, other.y) &&
               qFuzzyCompare(z, other.z);
    }

    bool operator!=(const Coordinate& other) const {
        return !(*this == other);
    }
};

// 状态表主结构体
struct StatusTable {
    // 核心状态字段
    RunStatus runStatus;                    // 运行状态
    AlarmStatus alarmStatus;                // 报警状态
    ControlMode controlMode;                // 控制方式
    MachineMode machineMode;                // 机台模式

    // 连接状态字段
    int cameraConnected;                   // 相机连接状态 (0-未连接, 1-已连接)
    int deviceConnected;                   // 机台设备连接状态 (0-未连接, 1-已连接)

    // 主轴加工参数
    double temperature;                     // 温度
    double torque;                          // 主轴扭矩(N·m)
    int spindleSpeed;                       // 主轴转速
    int feedSpeed;                          // 进给速度
    int pointMotionSpeed;                   // 点动速度
    double toolDiameter;                    // 刀具直径
    double lineSpacing;                     // 行刀间距
    double totalCuttingDepth;               // 切削总深
    int clearanceSpeed;                     // 空隙速度
    double workSurfaceHeight;               // 工作表面高度
    double cuttingDepth;                    // 吃刀深度
    double stepDistance;                    // 步动距离

    // 夹具状态
    QString fixtureStatus;                  // 夹具状态

    // 坐标位置数据
    Coordinate absolutePosition;            // 绝对坐标
    Coordinate relativePosition;            // 相对坐标
    Coordinate workPosition;                // 工作坐标
    Coordinate remainingDistance;           // 剩余距离

    // 状态时间（用于数据库连接判断）
    QDateTime statusTime;                   // 状态时间

    // 构造函数
    StatusTable() :
        runStatus(RunStatus::Idle),
        alarmStatus(AlarmStatus::NoAlarm),
        controlMode(ControlMode::Local),
        machineMode(MachineMode::Manual),
        cameraConnected(0),
        deviceConnected(0),
        temperature(0.0),
        spindleSpeed(0),
        feedSpeed(0),
        pointMotionSpeed(0),
        toolDiameter(0.0),
        lineSpacing(0.0),
        totalCuttingDepth(0.0),
        clearanceSpeed(0),
        workSurfaceHeight(0.0),
        cuttingDepth(0.0),
        stepDistance(0.0),
        statusTime(QDateTime::currentDateTime())
    {}

    // 更新状态时间
    void updateStatusTime() {
        statusTime = QDateTime::currentDateTime();
    }


    // 获取运行状态文本
    QString getRunStatusText() const {
        switch (runStatus) {
        case RunStatus::Idle: return "空闲";
        case RunStatus::Initialized: return "初始化完成";
        case RunStatus::Running: return "运行";
        case RunStatus::Paused: return "暂停";
        case RunStatus::Stopped: return "停止";
        default: return "未知";
        }
    }

    // 获取报警状态文本
    QString getAlarmStatusText() const {
        switch (alarmStatus) {
        case AlarmStatus::NoAlarm: return "无报警";
        case AlarmStatus::HasAlarm: return "有报警";
        default: return "未知";
        }
    }

    // 获取控制方式文本
    QString getControlModeText() const {
        switch (controlMode) {
        case ControlMode::Local: return "本地";
        case ControlMode::Remote: return "远程";
        default: return "未知";
        }
    }

    // 获取机台模式文本
    QString getMachineModeText() const {
        switch (machineMode) {
        case MachineMode::Manual: return "手动";
        case MachineMode::Auto: return "自动";
        case MachineMode::SingleStep: return "单步";
        case MachineMode::Debug: return "调试";
        case MachineMode::Maintenance: return "维护";
        default: return "未知";
        }
    }

    // 检查是否处于运行状态
    bool isRunning() const {
        return runStatus == RunStatus::Running;
    }

    // 检查是否有报警
    bool hasAlarm() const {
        return alarmStatus == AlarmStatus::HasAlarm;
    }

    // 检查是否为远程控制
    bool isRemoteControl() const {
        return controlMode == ControlMode::Remote;
    }

    // 检查状态是否发生变化
    bool hasChanged(const StatusTable& other) const {
        return runStatus != other.runStatus ||
               alarmStatus != other.alarmStatus ||
               controlMode != other.controlMode ||
               machineMode != other.machineMode ||
               cameraConnected != other.cameraConnected ||
               deviceConnected != other.deviceConnected ||
               spindleSpeed != other.spindleSpeed ||
               feedSpeed != other.feedSpeed ||
               !qFuzzyCompare(toolDiameter, other.toolDiameter) ||
               absolutePosition != other.absolutePosition ||
               relativePosition != other.relativePosition;
    }

    // 转换为QVariantMap（用于数据库操作）
    QVariantMap toVariantMap(bool includeAllFields = false) const {
        QVariantMap map;

        // 必须包含的字段
        map["status_time"] = statusTime;

        // 核心状态字段
        map["c_run_status"] = static_cast<int>(runStatus);
        map["c_alarm_status"] = static_cast<int>(alarmStatus);
        map["c_control_mode"] = static_cast<int>(controlMode);
        map["c_machine_mode"] = static_cast<int>(machineMode);
        map["c_camera_connected"] = cameraConnected;
        map["c_device_connected"] = deviceConnected;

        // 加工参数 - 总是包含，使用实际值或默认值
        map["s_temperature"] = temperature;
        map["torque"] = torque;
        map["s_spindle_speed"] = spindleSpeed;
        map["s_feed_speed"] = feedSpeed;
        map["s_point_motion_speed"] = pointMotionSpeed;
        map["s_tool_diameter"] = toolDiameter;
        map["s_line_spacing"] = lineSpacing;
        map["s_total_cutting_depth"] = totalCuttingDepth;
        map["s_clearance_speed"] = clearanceSpeed;
        map["s_work_surface_height"] = workSurfaceHeight;
        map["s_cutting_depth"] = cuttingDepth;
        map["s_step_distance"] = stepDistance;

        // 夹具状态和坐标
        map["f_fixture_status"] = fixtureStatus;
        map["p_absolute_position"] = absolutePosition.toString();
        map["p_relative_position"] = relativePosition.toString();
        map["p_work_position"] = workPosition.toString();
        map["p_remaining_distance"] = remainingDistance.toString();

        return map;
    }

    // 从QVariantMap解析（从数据库读取时使用）
    void fromVariantMap(const QVariantMap& map) {
        // 状态时间
        if (map.contains("status_time"))
            statusTime = map["status_time"].toDateTime();

        // 核心状态字段
        if (map.contains("c_run_status"))
            runStatus = static_cast<RunStatus>(map["c_run_status"].toInt());
        if (map.contains("c_alarm_status"))
            alarmStatus = static_cast<AlarmStatus>(map["c_alarm_status"].toInt());
        if (map.contains("c_control_mode"))
            controlMode = static_cast<ControlMode>(map["c_control_mode"].toInt());
        if (map.contains("c_machine_mode"))
            machineMode = static_cast<MachineMode>(map["c_machine_mode"].toInt());

        // 连接状态字段
        if (map.contains("c_camera_connected"))
            cameraConnected = map["c_camera_connected"].toInt();
        if (map.contains("c_device_connected"))
            deviceConnected = map["c_device_connected"].toInt();

        // 主轴加工参数
        if (map.contains("s_temperature"))
            temperature = map["s_temperature"].toDouble();
        if (map.contains("torque"))  // 新增扭矩字段
            torque = map["torque"].toDouble();
        if (map.contains("s_spindle_speed"))
            spindleSpeed = map["s_spindle_speed"].toInt();
        if (map.contains("s_feed_speed"))
            feedSpeed = map["s_feed_speed"].toInt();
        if (map.contains("s_point_motion_speed"))
            pointMotionSpeed = map["s_point_motion_speed"].toInt();
        if (map.contains("s_tool_diameter"))
            toolDiameter = map["s_tool_diameter"].toDouble();
        if (map.contains("s_line_spacing"))
            lineSpacing = map["s_line_spacing"].toDouble();
        if (map.contains("s_total_cutting_depth"))
            totalCuttingDepth = map["s_total_cutting_depth"].toDouble();
        if (map.contains("s_clearance_speed"))
            clearanceSpeed = map["s_clearance_speed"].toInt();
        if (map.contains("s_work_surface_height"))
            workSurfaceHeight = map["s_work_surface_height"].toDouble();
        if (map.contains("s_cutting_depth"))
            cuttingDepth = map["s_cutting_depth"].toDouble();
        if (map.contains("s_step_distance"))
            stepDistance = map["s_step_distance"].toDouble();

        // 夹具状态
        if (map.contains("f_fixture_status"))
            fixtureStatus = map["f_fixture_status"].toString();

        // 坐标位置数据
        if (map.contains("p_absolute_position"))
            absolutePosition = Coordinate::fromString(map["p_absolute_position"].toString());
        if (map.contains("p_relative_position"))
            relativePosition = Coordinate::fromString(map["p_relative_position"].toString());
        if (map.contains("p_work_position"))
            workPosition = Coordinate::fromString(map["p_work_position"].toString());
        if (map.contains("p_remaining_distance"))
            remainingDistance = Coordinate::fromString(map["p_remaining_distance"].toString());
    }

    // 清空所有数据
    void clear() {
        *this = StatusTable();
    }

    // 转换为字符串（用于调试）
    QString toString() const {
        return QString("状态: %1, 报警: %2, 控制: %3, 模式: %4, 主轴: %5rpm, 坐标: %6, 更新时间: %7")
            .arg(getRunStatusText())
            .arg(getAlarmStatusText())
            .arg(getControlModeText())
            .arg(getMachineModeText())
            .arg(spindleSpeed)
            .arg(absolutePosition.toString())
            .arg(statusTime.toString("hh:mm:ss"));
    }
};



#endif // STATUS_TABLE_H
